<template>
<div>
    <!-- 展示具体小组信息的对话框 -->
    <KDialog v-model:showDialog="queryGroup.show">
      <template #header>
        <div style="font-size: 22px; font-family: 'Roboto Slab', serif">
          详细信息
        </div>
      </template>
      <el-scrollbar height="600px">
        <div style="font-family: 'Roboto Slab', serif;">
          <p><span class="QueryLabel">小组ID</span>{{ queryGroup.id }}</p>
          <p><span class="QueryLabel">小组名称</span>{{ queryGroup.name }}</p>
          <p><span class="QueryLabel">描述信息</span>{{ queryGroup.desc }}</p>
          <p><span class="QueryLabel">创建时间</span>{{ queryGroup.CreatedAt }}</p>
          <p><span class="QueryLabel">创建者</span>{{ queryGroup.Owner }}</p>
          <p><span class="QueryLabel">小组成员</span>{{ queryGroup.members }}</p>
        </div>
      </el-scrollbar>
    </KDialog>

    <!-- 退出小组的对话框 -->
    <KDialog v-model:showDialog="quitGroup.show">
      <template #header>
        <div style="font-size: 20px; font-family: 'Roboto Slab', serif">
          退出小组 QUIT
        </div>
      </template>
      <div align="center">
        <div style="font-size:18px;margin:30px 10px;">你确定要退出小组吗？</div>
        <div align="right">
          <button
            class="button primary"
            style="margin: 0 10px"
            @click="quitGroup.handleConfirm"
          >
            确定
          </button>
          <button @click="quitGroup.show = false" style="margin: 0 10px">
            取消
          </button>
        </div>
      </div>
    </KDialog>

    <section>
    <br>
    <KTitle3>我加入的小组 The Group I Joined</KTitle3>
    <br>
    <div v-if="joinedGroup.group_num == 0" style="min-height: 1000px">
      <el-empty description="你貌似没有加入任何小组" :image-size="200"/>
    </div>    

    <div v-else style="min-height: 1100px">
      <div
          v-for="c in joinedGroup.groups"
          :key="c.id"
        >
          <KCard style="margin: 40px; color: black">
            <template #header>
              <div style="display:flex;justify-content: space-between;}">
                <div
                  class="MyFont"
                  style="font-size: 22px; padding: 20px 10px 0px"
                >
                <span style="background-color:var(--mainColor);color:white;padding:8px;border-radius:.5em;">TEAM</span> &ensp; {{ c.name }}
                </div>
                <div>
                  <el-tooltip
                    content="查看小组详细信息"
                    placement="top"
                    effect="dark"
                  >
                    <button
                      style="
                        font-size: 12px;
                        margin: 20px 10px 0;
                        border-radius: 1.5em;
                      "
                      class="primary icon solid fa-comment-dots"
                      @click="queryGroup.query(c.id)"
                    >
                      细节
                    </button>
                  </el-tooltip>
                  <el-tooltip
                    content="小心！这部操作会退出这个小组"
                    placement="top"
                    effect="dark"
                  >
                    <button
                      style="
                        font-size: 12px;
                        margin: 20px 10px 0;
                        border-radius: 1.5em;
                      "
                      class="icon solid fa-door-open"
                      @click="quitGroup.quit(c.id)"
                    >
                      退出
                    </button>
                  </el-tooltip>
                </div>
              </div>
            </template>
            <div class="MyFont" style="font-size: 16px; padding: 10px">
              <p class="icon solid fa-object-group">
                &ensp;小组ID: {{ c.id }}
              </p>
              <p class="icon solid fa-closed-captioning">
                &ensp;小组描述:
                {{
                  c.desc
                    ? `「${c.desc}」`
                    : "无"
                }}
              </p>
              <p class="icon solid fa-hourglass-start">
                &ensp;创建时间:
                {{ makePrettyTime(c.CreatedAt) }}
              </p>
            </div>
          </KCard>
        </div>
    </div>
    
    </section>

    <section 
      v-if="joinedGroup.group_num > 0" 
      align="center" 
      style="font-family: 'Roboto Slab', serif"
    >
      <KPagination
        v-model:cur_page="joinedGroup.cur_page"
        :total="joinedGroup.total_pages"
        @click="joinedGroup.move"
      ></KPagination>
    </section>
</div>
</template>

<script>
import { useStore } from "vuex"
import { ElNotification, ElLoading } from "element-plus"
import { reactive, computed, onMounted } from "vue"
import { makePrettyTime } from "@/hook/format"

export default {
    name : "GroupJoin",
    setup() {
      let store = useStore()

      function updateData() {
        const loading = ElLoading.service({
          lock: true,
          text: '正在拉取您的信息中...',
          background: 'rgba(0, 0, 0, 0.8)',
          customClass: "MyLoading"
        })
        store.dispatch("groupJoinNum").then(function() {
          if (store.state.group.joinedGroupNum) {
            let queryIndice = joinedGroup.cur_page_index
            let start = queryIndice[0];
            let end = queryIndice[queryIndice.length - 1] + 1
            // 最后一条需要在总条目之内
            end = Math.min(end, store.state.group.joinedGroupNum)
            // 最后一条需要在100条请求条目之内
            end = Math.min(end, start + 100)

            store.dispatch("groupJoined", {start, end}).then(function() {
              loading.close()
              if (store.state.group.joinedGroups.length > 0) {}
              else {ElNotification({title: "Oops", message: "拉去初始化列表失败，错误信息: " + store.state.error})}
            })
          }
          else {
            loading.close()
            let message
            if (store.state.group.joinedGroupNum == 0) {
              message = "你还未加入任何小组，赶紧加入一个吧！"
            }
            else {
              message = "初始化失败！错误信息: " + store.state.error
            }
            ElNotification({title: "Oops", message: message})
            return
          }
        })
      }

      // 挂载后的初始化获取数据
      onMounted(updateData)


      let joinedGroup = reactive({
        item_num : 10,
        groups: computed(() => store.state.group.joinedGroups),
        group_num: computed(() => store.state.group.joinedGroupNum),
        total_pages: computed(() => Math.ceil(joinedGroup.group_num / joinedGroup.item_num)),
        cur_page : 1,
        last_page : undefined,
        cur_page_index: computed(() => {
          let indexes = [], start = (joinedGroup.cur_page - 1) * joinedGroup.item_num;
          for (let i = start; i < Math.min(start + joinedGroup.item_num, joinedGroup.group_num); ++ i) {
            indexes.push(i);
          }
          return indexes;
        }),
        move() {
          if (joinedGroup.last_page != joinedGroup.cur_page)
            updateData()
          joinedGroup.last_page = joinedGroup.cur_page
        }
      })

      let queryGroup = reactive({
        show: false,
        lastQueryGroupID : undefined,
        id : computed(() => store.state.group.groupQuery.id),
        name : computed(() => store.state.group.groupQuery.name),
        desc : computed(() => {
          if (store.state.group.groupQuery.desc)
            return store.state.group.groupQuery.desc
          else
            return "无"
        }),
        CreatedAt : computed(() => makePrettyTime(store.state.group.groupQuery.CreatedAt)),
        Owner : computed(() => {
          let owner = store.state.group.groupQuery.owner
          return `${owner.name} (ID ${owner.id})`
        }),  // 姓名与ID
        members : computed(() => {
          let mems = store.state.group.groupQuery.members || []
          let resmems = []
          for (let i = 0; i < mems.length; ++ i)
            resmems.push(`${mems[i].name}(ID ${mems[i].id})`)
          return (resmems.length == 0) ? "暂无" : resmems.join(", ") 
        }),
        query(groupID) {
          groupID = parseInt(groupID)        
          if (queryGroup.lastQueryGroupID == groupID) {    // 上一次请求是这个就不发送了
            queryGroup.show = true;
          }
          else {
            store.dispatch("queryGroup", {groupID}).then(function() {
              if (store.state.opSuccess === true) {
                store.state.opSuccess = undefined;
                queryGroup.show = true;
              }
              else {
                ElNotification({title : "Oops", message: "好像出了一点问题导致查询失败"})
              }
            })
          }
          queryGroup.lastQueryGroupID = groupID
        },
      });

      let quitGroup = reactive({
        show : false,
        groupID : undefined,
        quit(groupID) {
          quitGroup.show = true
          quitGroup.groupID = parseInt(groupID)
        },
        handleConfirm() {
          const loading = ElLoading.service({
            lock: true,
            text: '正在退出中...',
            background: 'rgba(0, 0, 0, 0.8)',
            customClass: "MyLoading"
          })

          store.dispatch("quitGroup", {groupID : quitGroup.groupID}).then(function() {
            if (store.state.opSuccess === true) {
              store.state.opSuccess = undefined
              store.dispatch("groupJoinNum").then(function () {
                if (store.state.group.joinedGroupNum) {
                  let start = 0;
                  let end = Math.min(store.state.group.joinedGroupNum, 100);
                  store.dispatch("groupJoined", { start, end }).then(()=>{loading.close()})
                }
                ElNotification({title : "退出成功！", message: "散是满天星"})
                quitGroup.show = false
                loading.close()
              })
            }
            else {
              ElNotification({title: "Oops", message:"退出失败，原因如下：" + store.state.error})
              loading.close()
              quitGroup.show = false
            }
          })
        }
      })

      return {
        joinedGroup,
        queryGroup,
        quitGroup,
        makePrettyTime
      }
    }
}
</script>

<style scoped>
.QueryLabel {
  font-size: auto;
  padding: 8px;
  margin-right: 10px;
  background-color: var(--mainColor);
  color: white;
  border-radius: 1.2em;
  font-family: "Roboto Slab", serif;
}
</style>